const v_shader_source = `
  attribute vec4 a_Position;
  attribute vec2 a_TexCoord;
  varying vec2 v_TexCoord;
  void main(){
    gl_Position = a_Position;
    v_TexCoord = a_TexCoord;
  }
`;

const f_shader_source = `
  precision mediump float;
  varying vec2 v_TexCoord;
  uniform sampler2D u_Sampler0;
  uniform sampler2D u_Sampler1;
  void main(){
    vec4 color0 = texture2D(u_Sampler0,v_TexCoord);
    vec4 color1 = texture2D(u_Sampler1,v_TexCoord);
    gl_FragColor =  color0 * color1;
  }
`;

window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  const gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  let verticesTexCoords = new Float32Array([-0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 1.0, 1.0]);

  let vertexTexCoordBuffer = gl.createBuffer();

  gl.bindBuffer(gl.ARRAY_BUFFER, vertexTexCoordBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, verticesTexCoords, gl.STATIC_DRAW);

  const FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 4, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
  gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT, false, 4 * FSIZE, 2 * FSIZE);
  gl.enableVertexAttribArray(a_TexCoord);
  initTextures(gl);
});

const initTextures = gl => {
  Promise.all([loadText(gl, 0, './image/tree.jpg'), loadText(gl, 1, './image/cat.jpg')]).then(value => {
    let pointNum = value[0];
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, pointNum);
  });
};
const loadText = (gl, textureID = 0, src) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    let texture = gl.createTexture();
    image.src = src;
    image.onload = () => {
      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
      gl.activeTexture(gl['TEXTURE' + textureID]);
      gl.bindTexture(gl.TEXTURE_2D, texture);

      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

      let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler' + textureID);
      gl.uniform1i(u_Sampler, textureID);

      resolve(4);
    };
  });

};